package com.elong.android.specialhouse.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.framework.netmid.response.IResponse;
import com.elong.myelong.usermanager.User;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@SuppressLint("NewApi")
public class AdsActivity extends BaseVolleyActivity<IResponse<?>> {
	private String TAG = "AdsActivity";
	public static final String URL = "url";
	private WebView mWebView;
	private Map<String, String> mMapRequest;
	private final static int ACTIVITY_LOGIN = 8;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			mAnimation = AnimationUtils.loadAnimation(AdsActivity.this, R.anim.push_right_out);
		} catch (Exception e) {
			Log.d(TAG, "Exception to get push_right_out Animation : " + e.toString());
		}
	}

	@Override
	protected void initContentView() {
		setContentView(R.layout.act_ads_activity);
		String title = getIntent().getStringExtra(JSONConstants.ATTR_TITLE);
		//产品说不要标题
		setHeader(TextUtils.isEmpty(title) ? "" :title);
		View head = this.findViewById(R.id.ads_head);
		head.setVisibility(View.GONE);

		String url = getIntent().getStringExtra(URL);
		//realUrl
        url = setRealUrl(title);
		mWebView = (WebView) findViewById(R.id.webView_ads);
		mWebView.loadUrl(url);
		WebSettings settings = mWebView.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		settings.setSupportZoom(true);
		settings.setUseWideViewPort(true);
		settings.setLoadWithOverviewMode(true);
		mWebView.setWebViewClient(mWebViewClient);
	}


	private boolean isStartLoad = true;
	private boolean isDestroy;

	private WebViewClient mWebViewClient = new WebViewClient() {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.d(TAG, "shouldOverrideUrlLoading url = " + url);
			if (!TextUtils.isEmpty(url)) {
				try {
					url = URLDecoder.decode(url, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				mMapRequest = urlRequest(url);
				Log.d(TAG, "shouldOverrideUrlLoading Base64Encoded mMapRequest = " + mMapRequest);
				//目前的网页参数
//					   try {
//						   for (String strRequestKey : mMapRequest.keySet()) {
//							   String strRequestValue = mMapRequest.get(strRequestKey);
//							   strRequestValue = new String(Base64.decode(strRequestValue.getBytes(), Base64.DEFAULT));
//							   mMapRequest.put(strRequestKey, strRequestValue);
//							   Log.d(TAG, "strRequestKey = " + strRequestKey + ", strRequestValue = " + strRequestValue);
//						   }
//					   } catch (Exception e) { // 用于捕获非base64异常
//						   e.printStackTrace();
//					   }
				Log.d(TAG, "shouldOverrideUrlLoading Base64Decoded mMapRequest = " + mMapRequest);
				url = url.trim();
				if (url.startsWith("http://m.elong.com/hotel/detail/") || url.contains("m.elong.com/hotel/detail/")) {
					if (isWindowLocked()) {
						return true;
					}
					if (!User.getInstance().isLogin()) {
						// TODO去登录页
//						Intent intent = new Intent(AdsActivity.this, LoginActivity.class);
//						Bundle bundle = new Bundle();
//						intent.putExtras(bundle);
//						startActivityForResult(intent, ACTIVITY_LOGIN);
					} else {
						gotoApartmentDetailsActivity();
					}
					return true;
				} else if (url.startsWith("http://m.elong.com/hotel/0101/nlist") || url.contains("m.elong.com/hotel/0101/nlist")
						|| url.startsWith("http://m.elong.com/hotel/goback")) {
					back();
					return  true;
				} else {
					view.loadUrl(url);
					return true;
				}
			}
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			if (isStartLoad) {
				showLoading();
				isStartLoad = false;
			} else {
				// 显示loadind圈圈
				findViewById(R.id.pb_webview_loading).setVisibility(View.VISIBLE);
			}
			findViewById(R.id.webview_error).setVisibility(View.GONE);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			dismissAllDialog();
			// 隐藏loadind圈圈
			findViewById(R.id.pb_webview_loading).setVisibility(View.GONE);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			if (isDestroy) {
				return;
			}
			dismissAllDialog();
			findViewById(R.id.webview_error).setVisibility(View.VISIBLE);
		}
	};

	private String setRealUrl(String title) {
		String realUrl = "http://www.elong.com";
		Resources resources = this.getResources();
		if (!TextUtils.isEmpty(title)) {
		    if (title.equals(resources.getString(R.string.banner_shanghai))) {
				realUrl = "file:///android_asset/banner_url/activity_shanghai.html";
			} else if (title.equals(resources.getString(R.string.banner_sanya))){
				realUrl = "file:///android_asset/banner_url/activity_sanya.html";
			}
		}
		return realUrl;
	}
	/**
	 * 解析出url参数中的键值对
	 * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
	 *
	 * @param URL url地址
	 * @return url请求参数部分
	 */
	public Map<String, String> urlRequest(String URL) {
		Map<String, String> mapRequest = new HashMap<String, String>();

		String[] arrSplit = null;

		//strUrlParam 为请求参数
		String strUrlParam = truncateUrlPage(URL);

		if (strUrlParam == null) {
			return mapRequest;
		}
		//每个键值为一组
		arrSplit = strUrlParam.split("[&]");
		int i = 0;
		for (String strSplit : arrSplit) {
			String[] arrSplitEqual = null;
			arrSplitEqual = strSplit.split("[=]");

			//解析出键值
			if (arrSplitEqual.length > 1) {
				//正确解析
				Log.d(TAG, "urlRequest key[" + i + "] = " + arrSplitEqual[0] + ", value = " + arrSplitEqual[1]);
				mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
				++i;
			} else {
				if (arrSplitEqual[0] != "") {
					//只有参数没有值，不加入
					mapRequest.put(arrSplitEqual[0], "");
					Log.d(TAG, "urlRequest key[" + i + "] = " + arrSplitEqual[0] + ", value = ");
					++i;
				}
			}
		}
		return mapRequest;
	}

	/**
	 * 去掉url中的路径，留下请求参数部分
	 *
	 * @param strURL url地址
	 * @return url请求参数部分
	 */
	private String truncateUrlPage(String strURL) {
		String strAllParam = null;
		String[] arrSplit = null;

		strURL = strURL.trim();

		arrSplit = strURL.split("[?]");
		if (strURL.length() > 1) {
			if (arrSplit.length > 1) {
				if (arrSplit[1] != null) {
					strAllParam = arrSplit[1];
				}
			}
		}

		return strAllParam;
	}

	public void back() {
		dismissAllDialog();
		super.back();
	}


	private Animation mAnimation = null;

	/**
	 * 按键响应，在WebView中查看网页时，按返回键的时候按浏览历史退回,如果不做此项处理则整个WebView返回退出
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Check if the key event was the Back button and if there's history
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (mWebView.canGoBack() && event.getRepeatCount() == 0) {
				// 返回键退回
				mWebView.goBack();
				// 添加界面切换效果，注意只有Android的2.0(SdkVersion版本号为5)以后的版本才支持
				if (null != mAnimation) {
					mWebView.setAnimation(mAnimation);
				}
				return true;
			}
		}
		// If it wasn't the Back key or there's no web page history, bubble up
		// to the default
		// system behavior (probably exit the activity)
		return super.onKeyDown(keyCode, event);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Activity.RESULT_OK == resultCode) {
			switch (requestCode) {
				case ACTIVITY_LOGIN:
					if (User.getInstance().isLogin()) {
					    gotoApartmentDetailsActivity();
					}
					break;
				default:
					break;
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isDestroy = true;
		clearData();
		mWebView = null;
	}

	private void gotoApartmentDetailsActivity() {
		if (null != mMapRequest) {
			Intent intent = new Intent(AdsActivity.this, ApartmentDetailsActivity.class);
			Long houseId = 0L;
			if (mMapRequest.containsKey("id") && !TextUtils.isEmpty(mMapRequest.get("id"))) {
				try {
				    houseId = Long.parseLong(mMapRequest.get("id"));
				} catch (Exception e) {
					Log.d(TAG, "gotoApartmentDetailsActivity e : " + e.toString());
				}
			}
			Log.d(TAG, "shouldOverrideUrlLoading houseId = " + houseId);
			intent.putExtra(AppConstants.APARTMENT_ID, houseId);
			startActivity(intent);
		}
	}

	private void clearData() {
		clearWebviewData();
	}

	private void clearWebviewData() {
		String className = this.getClass().getSimpleName().toString();
		if (null != mWebView && TAG.equals(className)) {
			mWebView.removeAllViews();
			mWebView.clearHistory();
			clearCookie(this);
			mWebView.destroy();
		}
	}

	/**
	 * 清理webview的缓存
	 *
	 * @param @param context
	 * @return void
	 * @throws
	 * @Title: clearCookie
	 * @Description: TODO
	 */
	private void clearCookie(Context context) {
		if (null == context) {
			return;
		}
		CookieSyncManager.createInstance(context);
		if (CookieManager.getInstance() != null) {
			CookieManager.getInstance().removeAllCookie();
		}
	}
}
